package comum;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Client implements Serializable {

	protected String ip;
	protected int port;
	protected String ipServer;
	protected int portServer;
	
	public Client(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}
	
	public Client(String ip, String port) {
		this.ip = ip;
		this.port = Integer.parseInt(port) ;
	}
	
	public String getClientId() {
		return this.getIp()+":"+this.getPort();
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}
	
	

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	public void setPort(String port) {
		this.port = Integer.parseInt(port);
	}
	
	
	
	public String getIpServer() {
		return ipServer;
	}

	public void setIpServer(String ipServer) {
		this.ipServer = ipServer;
	}

	public int getPortServer() {
		return portServer;
	}

	public void setPortServer(int portServer) {
		this.portServer = portServer;
	}
	public void setPortServer(String portServer) {
		this.portServer = Integer.parseInt(portServer);
	}
	
	
	

	public boolean sendMessageToServer(String type, String message) {
		Mensagem msg = new Mensagem();
		msg.setIp(ipServer);
		msg.setPort(portServer);
		msg.setType(type);
		msg.setMessage(message);
		return msg.send();
	}
	
	/*public boolean sendMessageToServer(String type, byte[] message) {
		Mensagem msg = new Mensagem();
		msg.setIp(ipServer);
		msg.setPort(portServer);
		msg.setType(type);
		msg.setMessage(message);
		return msg.send();
	}*/
	
	public boolean sendMessageToClient(String type, String message) {
		Mensagem msg = new Mensagem();
		msg.setIp(ip);
		msg.setPort(port);
		msg.setType(type);
		msg.setMessage(message);
		return msg.send();
	}
	
	/*public boolean sendMessageToClient(String type, byte[] message) {
		System.out.println("Enviar");
		System.out.println(message);
		Mensagem msg = new Mensagem();
		msg.setIp(ip);
		msg.setPort(port);
		msg.setType(type);
		msg.setMessage(message);
		return msg.send();
	}*/
	
	
	public byte[] serialize() throws IOException {
		ObjectOutput out;
		ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
		out = new ObjectOutputStream(bos);
		out.writeObject(this);
	    out.close();
	    byte[] buf = bos.toByteArray();
	    return buf;
	}
	
	public static Client deserialize(byte[] buffer) throws IOException, ClassNotFoundException {
	    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer));
	    Client client = (Client) in.readObject();
	    in.close();
	    return client;
	}
	
	
}
